<template>
	<view class="container">
		<scroll-view v-if="list.length" scroll-y="true" class="scroll-Y">
			<view class="list_item" @click="toDetails(item.id)" v-for="item in list" :key="item.id">
				<view class="order_status">
					<view class="status">{{setOrderStatus(item.status)}}</view>
					<view @click.stop="openPaymentPopup(item)" class="status" v-if="item.status==10"
						style="background-color: #ff914d;color: #fff;border-color: #ff914d;">立即付款</view>
					<view @click.stop="showPopup(item)" v-if="item.status==30" class="refund">退款</view>
					<view class="order_del" style="" @click.stop="showDelPopup(item)"
						v-if="item.status==10||item.status==20">刪除</view>
				</view>
				<view class="top">
					<view class="left_img">
						<u-image :src="item.room_image" :lazy-load="true"></u-image>
					</view>
					<view class="name_orderNo">
						<view class="order_no">{{item.room_name}}</view>
						<view class="order_no">{{item.order_no}}</view>
					</view>
				</view>
				<view class="date_time_box">
					<!-- <view class="time"> -->
					<view class="time_box">
						<view class="top">{{orderStartDate(item.start)}}</view>
						<view class="">{{orderStartTime(item.start)}}</view>
					</view>
					<view class="time_box">
						<view class="top">時長</view>
						<view class="">{{orderDuration(item.start)}}</view>
					</view>
					<view class="time_box">
						<view class="top">{{orderEndDate(item.start)}}</view>
						<view class="">{{orderEndTime(item.start)}}</view>
					</view>
					<!-- </view> -->
				</view>

				<view class="order_money">支付金額：<text>${{item.total_price}}</text></view>
				<view class="order_time">下單時間：{{item.time}}</view>
			</view>
		</scroll-view>
		<view v-else style="padding: 30rpx;text-align: center;color: #;">暫無訂單</view>

		<u-modal :show="show" @confirm="confirmRefund" @cancel="show=false" @close="show=false" title='是否確認退款'
			confirmText="確認" :closeOnClickOverlay="true" :showCancelButton="true"></u-modal>

		<u-popup :closeOnClickOverlay="true" @close="showPeymentPopup=false" :show="showPeymentPopup" round="10">
			<view class="pay_box">
				<view class="title">立即付款</view>
				<view class="money">${{orderInfo.total_price}}</view>
				<view class="pay_type">
					<u-radio-group placement="column" v-model="radioValue" @change="groupChane">
						<u-radio customStyle="margin:0 30rpx 30rpx;" labelSize="20" activeColor="#ff914d" size="20"
							iconSize="20" v-for="item in pay_type" :label="item.name" :name="item.name"></u-radio>
					</u-radio-group>
					<view v-if="radioValue=='餘額付款'" class="balance">餘額：${{userStoreInfo.balance}}</view>
				</view>

				<view class="pay_type">
					<u-button @click="confirmPay" class="custom-style" text="立即支付"></u-button>
				</view>
			</view>
		</u-popup>

		<u-modal :show="showDel" @confirm="confirmDel" @close="showDel=false" @cancel="showDel=false"
			:showCancelButton="true" :closeOnClickOverlay="true">
			<view class="">是否確認刪除該訂單</view>
		</u-modal>
	</view>
</template>

<script>
	import {
		getOrderList,
		cancelOrder,
		orderPay,
		orderDel,
		getLinePayInfo,
	} from '@/api/order.js'
	import {
		getUserStoreInfo
	} from '@/api/me.js'
	export default {
		data() {
			return {
				list: [],
				store_id: '',
				page: 1,
				flag: true,
				userInfo: null,
				orderInfo: {},
				show: false,
				showPeymentPopup: false,
				pay_type: [{
						name: '餘額付款'
					},
					// {
					// 	name: '信用卡/轉帳 藍新'
					// },
					// {
					// 	name: '信用卡/轉帳 緑界'
					// }
				],
				radioValue: '餘額付款',
				userStoreInfo: {},
				showDel: false,
				osName: '',
				first: false,
				systemInfo: '',
				isLinePay: { // 判断是否唤醒linepay 支付
					flag: false,
					info: null,
				},
			};
		},
		onLoad(options) {
			this.store_id = options.store_id
			this.userInfo = JSON.parse(uni.getStorageSync('userInfo'))

			this.getOrderListFn(this.page)
			uni.getSystemInfo({
				success: (res) => {
					this.osName = res.osName
				}
			})
		},
		onShow() {
			if (this.isLinePay.flag && this.isLinePay.info) {
				uni.showLoading({
					title: '加载中...'
				})
				setTimeout(() => {
					getLinePayInfo({
						...this.isLinePay.info
					}).then(res => {
						console.log(res)
						if (res.code == 1) {
							uni.showToast({
								title: res.msg,
								icon: 'success',
								duration: 6000
							})
							setTimeout(() => {
								uni.reLaunch({
									url: `/pages/order_details/order_details?id=${res.data.id}`
								})
							}, 1500)
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none',
								duration: 6000
							})
						}
					})
				}, 1000)
			}
		},
		methods: {
			getOrderListFn(page) {
				const params = {
					user_id: this.userInfo.id,
					store_id: this.store_id,
					page,
				}
				getOrderList(params).then(res => {
					page > 1 ? this.list = this.list.concat(res.data) : this.list = res.data
				})
			},
			setOrderStatus(status) {
				switch (status) {
					case 10:
						return '待付款';
					case 20:
						return '已取消';
					case 30:
						return '待使用';
					case 31:
						return '已使用';
					case 32:
						return '已過期';
					case 33:
						return '進行中';
					case 40:
						return '待退款';
					case 41:
						return '已退款';
				}
			},
			orderStartDate(time) {
				let a = time.split('~')[0].trim().split(' ')[0]
				let b = new Date(a).getDay()
				return this.setWeek(a, b)
			},
			orderStartTime(time) {
				return time.split('~')[0].trim().split(' ')[1]
			},
			orderEndDate(time) {
				let a = time.split('~')[1].trim().split(' ')[0]
				let b = new Date(a).getDay()
				return this.setWeek(a, b)
			},
			orderEndTime(time) {
				return time.split('~')[1].trim().split(' ')[1]
			},
			setWeek(date, week) {
				switch (week) {
					case 0:
						return date + '週日';
					case 1:
						return date + '週一';
					case 2:
						return date + '週二';
					case 3:
						return date + '週三';
					case 4:
						return date + '週四';
					case 5:
						return date + '週五';
					case 6:
						return date + '週六';
				}
			},
			orderDuration(time) {

				if (this.osName == 'ios') {
					time = time.replace(/-/g, '/')
				}
				let start = time.split('~')[0]
				let end = time.split('~')[1]

				let a = new Date(end).getTime() - new Date(start).getTime()
				let h = Math.floor(a / 60 / 60 / 1000)
				let m = Math.floor((a % (60 * 60 * 1000) / 60 / 1000))
				if (m > 0) {
					return h + '小時' + m + '分鐘'
				} else {
					return h + '小時'
				}
			},
			showPopup(item) {
				this.show = true
				this.orderInfo = item
			},
			confirmRefund() {
				cancelOrder({
					order_id: this.orderInfo.id
				}).then(res => {
					this.show = false
					if (res.code == 1) {
						uni.showToast({
							title: '退款成功',
							icon: 'success'
						})
						this.getOrderListFn(1)
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 2000
						})
					}
				})
			},
			openPaymentPopup(item) {
				this.orderInfo = item
				this.showPeymentPopup = true
				this.getUserStoreInfoFn()
			},
			getUserStoreInfoFn() {
				getUserStoreInfo({
					store_id: this.orderInfo.store_id
				}).then(res => {
					this.userStoreInfo = res.data
					this.setPayment(res.data.pay_type_list)
				})
			},
			setPayment(arr) {
				if (this.first) return
				this.first = true
				arr.forEach(item => {
					/*
					switch (item) {
						case 1:
							this.pay_type.push({
								name: '信用卡/轉帳 藍新'
							})
							break;
						case 2:
							this.pay_type.push({
								name: '信用卡/轉帳 緑界'
							})
							break;
						case 4:
							this.pay_type.push({
								name: 'Line Pay'
							})
							break;
						case 9:
							this.pay_type.push({
								name: 'Apple pay'
							})
							break;
						case 10:
							this.pay_type.push({
								name: 'Google pay'
							})
							break;
					}
					*/

					switch (item) {
						case 1:
							this.pay_type.push({
								name: '信用卡/轉帳 藍新'
							})
							if (this.osName == 'ios' && this.store_id == 76) {
								this.pay_type.push({
									name: 'Apple pay',
								})
							}
							break;
						case 2:
							this.pay_type.push({
								name: '信用卡/轉帳 綠界'
							})
							break;
						case 4:
							if (this.store_id == 76) {
								this.pay_type.push({
									name: 'Line Pay',
								})
							}
							break;
							// case 9:
							// 	if (this.store_id == 76) {
							// 		this.pay_type.push({
							// 			name: 'Apple pay',
							// 		})
							// 	}

							// 	break;
							// case 10:
							// 	if (this.osName === 'android') {
							// 		this.pay_type.push({
							// 			name: 'Google pay',
							// 		})
							// 	}
							// 	break;
					}
				})
			},
			groupChane(e) {
				// console.log(e)
				this.radioValue = e
			},
			confirmPay() {
				// console.log(this.orderInfo)
				let pay_type = ''
				switch (this.radioValue) {
					case '信用卡/轉帳 藍新':
						pay_type = 1
						break;
					case '信用卡/轉帳 緑界':
						pay_type = 2
						break;
					case '超商付款':
						pay_type = 3
						break;
					case 'Line Pay':
						pay_type = 4
						break;
					case '儲值機':
						pay_type = 5
						break;
					case '餘額付款':
						pay_type = 6
						break;
					case '儲值卡':
						pay_type = 7
						break;
					case '電子票券':
						pay_type = 8
						break;
					case 'Apple pay':
						pay_type = 9
						break;
				}
				this.paymentFn(pay_type)
			},
			paymentFn(pay_type) {
				const params = {
					order_id: this.orderInfo.id,
					pay_type
				}
				orderPay(params).then(res => {
					this.paymentResult(res, pay_type)
				})
			},
			paymentResult(res, pay_type) {
				if (res.code !== 1) {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				} else {
					uni.setStorageSync('MerchantTradeNo', res.data.MerchantTradeNo)
					this.showPeymentPopup = false

					switch (pay_type) {
						case 1:
							uni.navigateTo({
								url: `/pages/book_now/outward_payment/outward_payment?payData=${JSON.stringify(res.data)}&type=1`
							})
							break;
						case 2:
							uni.navigateTo({
								url: `/pages/book_now/outward_payment/outward_payment?form=${JSON.stringify(res.data)}&type=2`
							})
							break;
						case 4:
							this.isLinePay = {
								flag: true,
								info: res.data.pay_log
							}
							this.wakeUp(res.data.result)

							break;
						case 6:
							uni.showToast({
								title: '付款成功',
								icon: 'success'
							})
							getOrderList({
								page: 1,
								status: this.tabIndex
							}).then(res => {
								// console.log(res.data, '訂單列表')
								this.order_list = res.data
							})
							break
					}
				}
			},
			showDelPopup(item) {
				this.showDel = true
				this.orderInfo = item
			},
			confirmDel() {
				orderDel({
					order_id: this.orderInfo.id
				}).then(res => {
					uni.showToast({
						title: '刪除成功',
						icon: 'success'
					})
					this.showDel = false
				}).then(() => {
					this.getOrderListFn(1)
				})
			},
			toDetails(id) {
				uni.navigateTo({
					url: `/pages/order_details/order_details?id=${id}`
				})
			},
			determine() {
				const install = plus.runtime.isApplicationExist()
				return install
			},
			// 唤醒line pay
			wakeUp(path) {
				const systemInfo = uni.getSystemInfoSync()
				// #ifdef APP-PLUS
				if (systemInfo.platform === 'Android') {
					const params = {
						pname: 'jp.naver.line.android',
						action: 'line://'
					}
					if (this.determine(params)) {
						// 已下載line pay
						plus.runtime.openURL(path, function() {
							// plus.nativeUI.alert('本機未安裝指定的應用')
						})
					} else {
						plus.runtime.openURL(`market://details?id=${params.pname}`, function() {
							// plus.nativeUI.alert('本機未安裝指定的應用')
						})
					}
				} else if (systemInfo.platform === 'ios') {
					const params = {
						appid: ''
					}
					plus.runtime.launchApplication({
						action: path
					}, function() {
						plus.nativeUI.actionSheet({
							title: '應用市場',
							cancel: '取消',
							buttons: [{
								title: '應用市場'
							}]
						}, function({
							index
						}) {
							switch (index) {
								case 1:
									plus.runtime.openURL(
										`itms-apps://itunes.apple.com`,
										function() {
											// plus.nativeUI.alert('本機未安裝指定的應用')
										})
							}
						})
					})
					// this.determine()
					plus.runtime.openURL(path, function() {
						// plus.nativeUI.alert('本機未安裝指定的應用')
					})
				}
				// #endif

				// #ifdef H5
				// uni.navigateTo({
				// 	url: `/pages/book_now/outward_payment/outward_payment?url=${path}&type=4`
				// })

				const userAgent = navigator.userAgent
				if (/(Android)/i.test(userAgent)) {
					// Android平台
					window.location.href = path
				} else if (/iPhone|iPad|iPod/i.test(userAgent)) {
					// ios平台
					window.location.href = path
				}

				// #endif

			},
		}
	}
</script>

<style lang="less" scoped>
	.container {
		padding: 20rpx 30rpx;
		box-sizing: border-box;
		background-color: #f7f7f7;

		.scroll-Y {
			height: 90vh;

			// background-color: skyblue;
			.list_item {
				margin-bottom: 20rpx;
				background-color: #fff;
				padding: 20rpx;
				border-radius: 10rpx;

				position: relative;

				.order_status {
					position: absolute;
					right: 20rpx;
					// top: 30rpx;

					.status {
						background-color: #39B19D;
						color: #fff;
						width: 140rpx;
						height: 45rpx;
						border-radius: 10rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						margin-bottom: 20rpx;
					}

					.refund {
						// border: 1rpx solid #ff914d;
						// color: #ff914d;
						background-color: #ff914d;
						color: #fff;
						width: 140rpx;
						height: 45rpx;
						border-radius: 10rpx;
						display: flex;
						align-items: center;
						justify-content: center;
					}

					.order_del {
						background-color: red;
						color: #fff;
						border-color: red;
						width: 140rpx;
						height: 45rpx;
						border-radius: 10rpx;
						display: flex;
						align-items: center;
						justify-content: center;
					}
				}

				.top {
					display: flex;
					align-items: center;
					margin-bottom: 15rpx;

					.left_img {
						width: 180rpx;
						height: 120rpx;
						margin-right: 20rpx;

						/deep/ .u-image {
							width: 180rpx !important;
							height: 120rpx !important;
							border-radius: 10rpx !important;
						}

						/deep/ .u-image__image {
							width: 180rpx !important;
							height: 120rpx !important;
							border-radius: 10rpx !important;
						}

						/deep/ .u-image__loading {
							width: 180rpx !important;
							height: 120rpx !important;
							border-radius: 10rpx !important;
						}

						/deep/ .u-image__error {
							width: 180rpx !important;
							height: 120rpx !important;
							border-radius: 10rpx !important;
						}
					}

					.name_orderNo {
						.order_no {
							margin-bottom: 10rpx;
							font-size: 30rpx;
						}
					}
				}

				.date_time_box {
					display: flex;
					justify-content: space-around;
					margin-top: 50rpx;
					margin-bottom: 20rpx;

					.time_box {
						text-align: center;
						display: flex;
						flex-direction: column;
						align-items: center;

						.top {
							margin-bottom: 10rpx;
						}
					}
				}

				.order_money,
				.order_time {
					font-size: 30rpx;
					font-weight: 400;
					margin-bottom: 6rpx;

					text {
						color: #FA533D;
						font-size: 32rpx;
					}
				}
			}
		}
	}

	.pay_box {
		height: 60vh;
		padding: 30rpx;
		box-sizing: border-box;

		.title {
			font-size: 32rpx;
			text-align: center;
			margin-bottom: 40rpx;
		}

		.money {
			color: #ff914d;
			font-weight: 600;
			font-size: 48rpx;
			text-align: center;
			margin-bottom: 60rpx;
		}

		.pay_type {
			margin-top: 100rpx;
			position: relative;

			.balance {
				position: absolute;
				top: 0rpx;
				right: 0%;
				font-size: 30rpx;
				color: #ff914d;
			}

			.custom-style {
				background-color: #39B19D;
				color: #fff;
				width: 500rpx;
			}
		}

	}
</style>